<template>
  <div class="p-2">
    <el-tabs type="border-card" @tab-click="tabClick">
      <!-- <el-tab-pane label="规则任务池" v-if="isExpert">
        <div class="search" v-show="showSearch">
          <el-form
            :model="uncheckQueryParams"
            ref="queryFormRef"
            :inline="true"
            label-width="68px"
          >
            <el-form-item label="课程名称" prop="name">
              <el-input
                v-model="uncheckQueryParams.name"
                placeholder="请输入课程名称"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item label="团队名称" prop="type">
              <el-input
                v-model="uncheckQueryParams.name"
                placeholder="请输入课程名称"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item label="课程分类" prop="type">
              <el-select
                v-model="uncheckQueryParams.sourceType"
                clearable
                placeholder="Select"
              >
                <el-option
                  v-for="item in selectArr.typeArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="提交时间" prop="age">
              <el-date-picker
                v-model="uncheckQueryParams.time"
                type="datetimerange"
                range-separator="To"
                start-placeholder="Start date"
                end-placeholder="End date"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery"
                >搜索</el-button
              >
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <el-table
            v-loading="loading"
            :data="politicsList"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="30" align="center" />

            <el-table-column
              label="课程名称"
              align="center"
              prop="name"
              v-if="true"
            />

            <el-table-column label="创建者" align="center" prop="createBy" />
            <el-table-column
              label="团队名称"
              align="center"
              prop="introduction"
            />

            <el-table-column
              label="提交审核时间"
              align="center"
              prop="createTime"
              width="180"
            />

            <el-table-column
              label="审核结果"
              align="center"
              prop="createTime"
              width="180"
            />

            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
              width="220"
            >
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  @click="handleDetail(scope.row, false)"
                  >查看详情</el-button
                >
                <el-button link type="primary" @click="grabTask(scope.row)"
                  >我要审核</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          分页组件 
          <pagination
            v-show="politicsTotal > 0"
            :total="politicsTotal"
            v-model:page="getPoliticsListParams.pageNum"
            v-model:limit="getPoliticsListParams.pageSize"
            @pagination="getPoliticsPoolList"
          />

          <el-dialog
            v-model="dialogStatus.isPoliticsDetail"
            :title="dialogStatus.title"
            width="70%"
            center
            :show-close="true"
            :close-on-click-modal="false"
            @close="closeDialog"
            destroy-on-close
          >
            <dialog-form
              :courseInfo="courseInfo"
              :checkTaskBO="checkTaskBO"
              @closeDialog="closeDialog"
            >
            </dialog-form>
          </el-dialog>
        </div>
      </el-tab-pane> -->
      <el-tab-pane label="待审核" v-if="isExpert">
        <div class="search" v-show="showSearch">
          <el-form
            :model="uncheckQueryParams"
            ref="queryFormRef"
            :inline="true"
            label-width="68px"
          >
            <el-form-item label="课程名称" prop="name">
              <el-input
                v-model="uncheckQueryParams.name"
                placeholder="请输入课程名称"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item label="团队名称" prop="type">
              <el-input
                v-model="uncheckQueryParams.name"
                placeholder="请输入课程名称"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item label="课程分类" prop="type">
              <el-select
                v-model="uncheckQueryParams.sourceType"
                clearable
                placeholder="Select"
              >
                <el-option
                  v-for="item in selectArr.typeArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="提交时间" prop="age">
              <el-date-picker
                v-model="uncheckQueryParams.time"
                type="datetimerange"
                range-separator="To"
                start-placeholder="Start date"
                end-placeholder="End date"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery"
                >搜索</el-button
              >
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <el-table
            v-loading="loading"
            :data="contentList"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="30" align="center" />

            <el-table-column
              label="课程名称"
              align="center"
              prop="name"
              v-if="true"
            />

            <el-table-column label="创建者" align="center" prop="createBy" />
            <el-table-column
              label="团队名称"
              align="center"
              prop="introduction"
            />
            <el-table-column
              label="最多审核人数"
              align="center"
              prop="maxNum"
            />
            <el-table-column
              label="已审核人数"
              align="center"
              prop="currentNum"
            />

            <el-table-column
              label="提交审核时间"
              align="center"
              prop="createTime"
              width="180"
            />

            <el-table-column
              label="审核结果"
              align="center"
              prop="createTime"
              width="180"
            />

            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
              width="220"
            >
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  v-hasPermi="['system:examineTask:query']"
                  @click="handleDetail(scope.row, true)"
                  >开始审核</el-button
                >
                <!-- <el-button
                  link
                  type="primary"
                  @click="preemptCheckTask(scope.row)"
                  >添加审核任务</el-button
                > -->
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页组件 -->
          <pagination
            v-show="contentTotal > 0"
            :total="contentTotal"
            v-model:page="getContentListParams.pageNum"
            v-model:limit="getContentListParams.pageSize"
            @pagination="getUnCheckList"
          />
        </div>

        <el-dialog
          v-model="dialogStatus.isContentDetail"
          :title="dialogStatus.title"
          width="70%"
          center
          :show-close="true"
          :before-close="isClose"
          @close="closeDialog"
          destroy-on-close
        >
          <dialog-form
            :courseInfo="courseInfo"
            :checkTaskBO="checkTaskBO"
            @closeDialog="closeDialog"
          >
          </dialog-form>
        </el-dialog>
      </el-tab-pane>
      <el-tab-pane :label="isExpert ? '审核中' : '待审核'">
        <div class="search" v-show="showSearch">
          <el-form
            :model="uncheckQueryParams"
            ref="queryFormRef"
            :inline="true"
            label-width="68px"
          >
            <el-form-item label="课程名称" prop="name">
              <el-input
                v-model="uncheckQueryParams.name"
                placeholder="请输入课程名称"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item label="团队名称" prop="type">
              <el-input
                v-model="uncheckQueryParams.name"
                placeholder="请输入课程名称"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item label="课程分类" prop="type">
              <el-select
                v-model="uncheckQueryParams.sourceType"
                clearable
                placeholder="Select"
              >
                <el-option
                  v-for="item in selectArr.typeArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="提交时间" prop="age">
              <el-date-picker
                v-model="uncheckQueryParams.time"
                type="datetimerange"
                range-separator="To"
                start-placeholder="Start date"
                end-placeholder="End date"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery"
                >搜索</el-button
              >
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <el-table
            v-loading="loading"
            :data="uncheckedList"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="30" align="center" />

            <el-table-column
              label="课程名称"
              align="center"
              prop="name"
              v-if="true"
            />

            <el-table-column label="创建者" align="center" prop="createBy" />
            <el-table-column
              label="团队名称"
              align="center"
              prop="introduction"
            />

            <el-table-column
              label="提交审核时间"
              align="center"
              prop="createTime"
              width="180"
            />

            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
              width="220"
            >
              <template #default="scope">
                <el-button
                  v-if="scope.row.examineStatusCode === 50"
                  link
                  type="primary"
                  v-hasPermi="['system:examineTask:query']"
                  @click="handleDetail(scope.row, true)"
                  >继续审核</el-button
                >
                <el-button
                  v-else
                  link
                  type="primary"
                  v-hasPermi="['system:examineTask:query']"
                  @click="handleDetail(scope.row, true)"
                  >{{ !scope.row.reason ? "开始审核" : "继续审核" }}</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页组件 -->
          <pagination
            v-show="unCheckTotal > 0"
            :total="unCheckTotal"
            v-model:page="uncheckQueryParams.pageNum"
            v-model:limit="uncheckQueryParams.pageSize"
            @pagination="getUnCheckList"
          />
        </div>

        <el-dialog
          v-model="dialogStatus.isFirstDetail"
          :title="dialogStatus.title"
          width="70%"
          center
          :show-close="true"
          @close="closeDialog"
          :before-close="isClose"
          destroy-on-close
        >
          <dialog-form
            :rejectCheckList="rejectCheckList"
            :courseInfo="courseInfo"
            :checkTaskBO="checkTaskBO"
            :schoolCheckList="schoolCheckList"
            @closeDialog="closeDialog"
          >
          </dialog-form>
        </el-dialog>
      </el-tab-pane>
      <el-tab-pane label="已审核">
        <div class="search" v-show="showSearch">
          <el-form
            :model="uncheckQueryParams"
            ref="queryFormRef"
            :inline="true"
            label-width="68px"
          >
            <el-form-item label="课程名称" prop="name">
              <el-input
                v-model="checkedQueryParams.name"
                placeholder="请输入课程名称"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item label="团队名称" prop="type">
              <el-input
                v-model="checkedQueryParams.name"
                placeholder="请输入课程名称"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item label="课程分类" prop="type">
              <el-select
                v-model="checkedQueryParams.sourceType"
                clearable
                placeholder="Select"
              >
                <el-option
                  v-for="item in selectArr.typeArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="提交时间" prop="age">
              <el-date-picker
                v-model="checkedQueryParams.time"
                type="datetimerange"
                range-separator="To"
                start-placeholder="Start date"
                end-placeholder="End date"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery"
                >搜索</el-button
              >
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <el-table
            v-loading="loading"
            :data="checkedList"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="30" align="center" />

            <el-table-column
              label="课程名称"
              align="center"
              prop="name"
              v-if="true"
            />

            <el-table-column label="创建者" align="center" prop="createBy" />
            <el-table-column
              label="团队名称"
              align="center"
              prop="introduction"
            />

            <el-table-column
              label="提交审核时间"
              align="center"
              prop="createTime"
              width="180"
            />

            <el-table-column label="审核结果" prop="online_status" width="160">
              <template #default="{ row }: { row: CourseCourseVo }">
                <el-tag :type="checkStatus(row.examineStatusMsg ?? '')"
                  >{{ row.examineStatusMsg }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
              width="220"
            >
              <template #default="scope">
                <el-button
                  v-show="!scope.row.termination"
                  link
                  type="primary"
                  v-hasPermi="['system:examineTask:query']"
                  @click="handleDetail(scope.row, false)"
                  >查看详情</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页组件 -->
          <pagination
            v-show="checkedTotal > 0"
            :total="checkedTotal"
            v-model:page="checkedQueryParams.pageNum"
            v-model:limit="checkedQueryParams.pageSize"
            @pagination="getCheckedList"
          />
        </div>
        <el-dialog
          v-model="dialogStatus.isSecondDetail"
          :title="dialogStatus.title"
          width="70%"
          center
          :show-close="true"
          destroy-on-close
          :before-close="isClose"
          @close="closeDialog"
        >
          <dialog-form
            :courseInfo="courseInfo"
            :checkTaskBO="checkTaskBO"
            @closeDialog="closeDialog"
            :otherExportCheckList="otherExportCheckList"
          >
          </dialog-form>
        </el-dialog>

        <!-- <el-dialog
          v-model="dialogStatus.setCourse"
          title="课程设置"
          width="35%"
          center
          :show-close="true"
          :close-on-click-modal="false"
          destroy-on-close
        >
          <el-form
            :model="courseInfo"
            ref="queryFormRef"
            label-position="left"
            label-width="120px"
          >
            <el-form-item label="是否为核心课程">
              <el-select
                :disabled="isCoreDisabled"
                v-model="courseInfo.core"
                placeholder="Select"
                size="large"
              >
                <el-option
                  v-for="item in selectArr.coreArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-button
                link
                type="primary"
                @click="isCoreDisabled = !isCoreDisabled"
              >
                修改
              </el-button>
              <el-button
                v-if="!isCoreDisabled"
                link
                type="primary"
                @click="handelSettingCore"
              >
                确定
              </el-button>
            </el-form-item>

            <el-form-item label="核心课程年级">
              <div v-if="courseInfo.grade">
                <el-select
                  v-if="isGradeDisabled"
                  :disabled="isGradeDisabled"
                  v-model="courseInfo.grade.id"
                  placeholder="Select"
                  size="large"
                >
                  <el-option
                    v-for="item in selectArr.gradeIdArr"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
                <el-select
                  v-else
                  v-model="addCourseGradeBO.gradeId"
                  placeholder="Select"
                  size="large"
                >
                  <el-option
                    v-for="item in selectArr.gradeIdArr"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
                <el-button
                  link
                  type="primary"
                  @click="isGradeDisabled = !isGradeDisabled"
                >
                  修改
                </el-button>
                <el-button
                  v-show="!isGradeDisabled"
                  link
                  type="primary"
                  @click="handelChangeGrade"
                >
                  确定1
                </el-button>
              </div>
              <div v-else>
                <el-select
                  v-model="addCourseGradeBO.gradeId"
                  placeholder="Select"
                  size="large"
                >
                  <el-option
                    v-for="item in selectArr.gradeIdArr"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>

                <el-button link type="primary" @click="handelAddGrade">
                  确定2
                </el-button>
              </div>
            </el-form-item>
            <el-form-item label="">
              <div style="margin: 5vh 0 0 8vw">
                <el-button @click="closeSetting"> 取消 </el-button>
              </div>
            </el-form-item>
          </el-form>
        </el-dialog> -->
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import {
  getUnCheckList as getUnCheckListApi,
  getCourseDetail as getCourseDetailApi,
  preemptCheckTask as preemptCheckTaskApi,
  getCheckTaskDetail as getCheckTaskDetailApi,
  getCheckedList as getCheckedListApi,
  getPoliticsPoolList as getPoliticsPoolListApi,
  getContentPoolList as getContentPoolListApi,
  getCheckRecord as getCheckRecordApi,
} from "@/service/api/course/check";
import dialogForm from "./dialogForm.vue";

import { useUserStore } from "@/store/modules/user.ts";
import { ElForm, menuItemEmits } from "element-plus";
import {
  CourseExamineStageMap,
  CourseExamineStatusMap,
  CourseExamineMapOfOperation,
} from "@/maps/course/examine/courseExamineStatusMap.ts";
import to from "await-to-js";
const queryFormRef = ref(ElForm);
const tableIds = ref<string[]>([]);
// 分页获取待审核任务
const initUncheckQueryParams = {
  createBy: "",
  name: "",
  remark: "",
  pageSize: 10,
  pageNum: 1,
  sourceType: "1",
  // 0-未审核 1-已审核
  status: "0",
};
// 分页获取已审核任务
const initCheckedQueryParams = {
  // 用户id
  examinerId: "",
  createBy: "",
  name: "",
  sourceType: "1",
  remark: "",
  pageSize: 10,
  pageNum: 1,
  // 0-未审核 1-已审核
  status: "1",
  hideRemedyTask: true,
};
// 分页获取政治审核列表
const initGetPoliticsListParams = {
  pageSize: 10,
  pageNum: 1,
  examineStatusCode: 4,
};
// 分页获取内容审核列表
const initGetContentListParams = {
  pageSize: 10,
  pageNum: 1,
  examineStatusCode: 5,
};
// 课程详情
const initCourseInfo = {
  id: "",
  examineStatusCode: 0,
  core: false,
  name: "",
  subtitle: "",
  organizationId: "",
  ownerId: "",
  sceneId: "",
  totalSection: 0,
  type: "",
  categoryId: "",
  remark: "",
  labelList: [],
  introduction: "",
  childAgeList: [],
  parentAgeList: [],
  grade: "",
  category: [],
  isOperate: false,
};

// 新增课程年级BO
const initAddCourseGradeBO = {
  courseId: "",
  gradeId: "",
};
// 初始dialog状态
const initDialogStatus = {
  isSecondDetail: false,
  isFirstDetail: false,
  isVisible: false,
  title: "",
  isDisabled: false,
  isPoliticsDetail: false,
  isContentDetail: false,
  setCourse: false,
};
// 审核任务详情BO
const initCheckTaskBO = {
  id: "",
  behavior: "",
  // 是否进入下一审批
  remedy: "",
  reason: "",
  additionalDataList: [
    {
      dataType: "courseScore",
      score: 0,
      type: "1",
    },
    {
      dataType: "courseScore",
      score: 0,
      type: "2",
    },
    {
      dataType: "courseScore",
      score: 0,
      type: "3",
    },
  ],
};
const data = reactive({
  uncheckQueryParams: { ...initUncheckQueryParams },
  checkedQueryParams: { ...initCheckedQueryParams },
  dialogStatus: { ...initDialogStatus },
  courseInfo: { ...initCourseInfo },
  checkTaskBO: { ...initCheckTaskBO },
  getPoliticsListParams: { ...initGetPoliticsListParams },
  getContentListParams: { ...initGetContentListParams },
  addCourseGradeBO: { ...initAddCourseGradeBO },
});

const {
  uncheckQueryParams,
  dialogStatus,
  courseInfo,
  checkTaskBO,
  checkedQueryParams,
  getPoliticsListParams,
  getContentListParams,
  addCourseGradeBO,
} = toRefs(data);

// 选择框数据
const selectArr = reactive({
  // 类型
  typeArr: [
    {
      value: "1",
      label: "读书",
    },
    {
      value: "2",
      label: "课程",
    },
  ],
  // 状态
  resourceRegionArr: [
    {
      value: "0",
      label: "组织私有",
    },
    {
      value: "1",
      label: "公共资源",
    },
    {
      value: "2",
      label: "全部资源",
    },
  ],
  // 孩子年龄列表
  childAgeArr: [],
  // 父母年龄列表
  parentAgeArr: [],
  // 场景列表
  sceneArr: [],
  // 二级分类列表
  catgroyList: [],
  // 标签列表
  labelList: [],
  // 是否为核心课程
  coreArr: [
    {
      value: true,
      label: "是",
    },
    {
      value: false,
      label: "否",
    },
  ],
  // 年级列表
  gradeIdArr: [
    {
      id: "000",
      name: "未设置",
    },
  ],
});

// const isCoreDisabled = ref(true);
// const isGradeDisabled = ref(true);

const single = ref(true);
const multiple = ref(true);
const showSearch = ref(true);
const loading = ref(false);
// 当前用户身份
const userIdentity = ref();
// 未审核total
const unCheckTotal = ref(0);
// 已审核total
const checkedTotal = ref(0);
// 政治审核total
const politicsTotal = ref(0);
// 内容审核total
const contentTotal = ref(0);
// 未审核列表
const uncheckedList = ref([]);
// 已审核列表
const checkedList = ref([]);
// 政治审核列表
const politicsList = ref([]);
// 内容审核列表
const contentList = ref([]);
// 是否是专家
const isExpert = ref(false);
// 获取待审核列表
const getUnCheckList = async () => {
  const res = await getUnCheckListApi(uncheckQueryParams.value);
  console.log(res);
  uncheckedList.value = res.rows;
  unCheckTotal.value = Number(res.total);
};

const isOperator = ref(false);
// 获取当前用户id
const getUserId = () => {
  let userInfo = useUserStore();
  checkedQueryParams.value.examinerId = userInfo.userId;
  userIdentity.value = userInfo.identityList;
  console.log(userIdentity.value);
  if (
    userIdentity.value.find((item: any) => {
      item.key === "operator";
      return true;
    })
  ) {
    isOperator.value = true;
  } else {
    isOperator.value = false;
  }
  // 判断是否是专家用户
  isExpert.value = userIdentity.value.some((obj: any) => {
    return obj.key === "expert";
  });
};

// 获取已审核列表
const getCheckedList = async () => {
  const res = await getCheckedListApi(checkedQueryParams.value);
  console.log(res);
  checkedList.value = res.rows;
  checkedTotal.value = Number(res.total);

  // 遍历所有课程
  checkedList.value.forEach((item: any) => {
    const examineStatus = String(item.examineStatusCode);
    if (examineStatus.charAt(0) === "6") {
      const status = examineStatus.charAt(1);
      const statusStr = CourseExamineMapOfOperation.get(status);
      item.examineStatusMsg = `${statusStr}`;
    } else {
      if (examineStatus.charAt(1) != "1" && item.termination) {
        item.examineStatusMsg = "内容团队终止";
      } else {
        const stage = examineStatus.charAt(0);
        const status = examineStatus.charAt(1);
        // if (examineStatus.length > 1) {
        //   var status = examineStatus.charAt(1);
        // }
        // console.log(status);

        const stageStr: string | undefined = CourseExamineStageMap.get(stage);
        const statusStr: string | undefined =
          CourseExamineStatusMap.get(status);

        if (stageStr == undefined || statusStr == undefined) {
          item.examineStatusMsg = "未提交审核";
        } else {
          item.examineStatusMsg = `${statusStr}`;
        }
      }
    }
  });
};

// 审核状态
const checkStatus = (status: string) => {
  let regPass = RegExp(/通过/);
  let regFinalPass = RegExp(/上架平台/);
  let regFinalChecking = RegExp(/待/);
  let regChecking = RegExp(/中/);
  let regRefuse = RegExp(/打回/);
  let regTermination = RegExp(/终止/);
  let regUncommitted = RegExp(/未/);

  if (regPass.test(status) || regFinalPass.test(status)) {
    return "success";
  } else if (regChecking.test(status) || regFinalChecking.test(status)) {
    return "warning";
  } else if (regRefuse.test(status) || regTermination.test(status)) {
    return "danger";
  } else if (regUncommitted.test(status)) {
    return "info";
  }
};

// 获取政治审核
const getPoliticsPoolList = async () => {
  const res = await getPoliticsPoolListApi(getPoliticsListParams.value);
  console.log(res);
  politicsList.value = res.rows;
  politicsTotal.value = Number(res.total);
};

// 获取内容审核列表
const getContentPoolList = async () => {
  const res = await getContentPoolListApi(getContentListParams.value);
  console.log(res);
  contentList.value = res.rows;
  contentTotal.value = Number(res.total);
};

// 提交查询按钮
const handleQuery = () => {
  getUnCheckList();
};

// 重置按钮
const resetQuery = () => {
  queryFormRef.value.resetFields();
  getUnCheckList();
};

// 获取区域树
const getRegionTree = async () => {};

// // 占有审核任务
// const preemptCheckTask = async (row: any) => {
//   const res = await preemptCheckTaskApi(row.id);
//   console.log(res);
//   if (res.code === 200) {
//     ElMessage({
//       message: "操作成功",
//       type: "success",
//     });
//     getContentPoolList();
//   }
// };
// 找到最后一个终止的位置
const lastRemedyIndex = (list: any) => {
  let lastIndex = -1;
  for (let i = list.length - 1; i >= 0; i--) {
    if (!list[i].remedy && list[i].examineStatusCode === 0) {
      lastIndex = i;
      break;
    }
  }
  return lastIndex;
};

// 子站驳回记录
const rejectCheckList: any = ref([]);
// 平台驳回记录
const platformCheckList: any = ref([]);
// 分别存放三个专家的审核记录
const exportMap = new Map();

// 获取平台审核部分每个专家的审核记录
const getEachExportCheckList = (checkList: any) => {
  // 遍历对象数组
  for (let item of checkList) {
    // 如果有examinerId
    if (item.examinerId) {
      // 如果idMap中还没有这个id
      if (!exportMap.has(item.examinerId)) {
        // 在idMap中添加这个id对应的空数组
        exportMap.set(item.examinerId, []);
      }
      // 将当前对象添加到该id对应的数组中
      exportMap.get(item.examinerId).push(item);
    } else {
      for (let checkItem of exportMap) {
        console.log(checkItem[1]);
        // if(checkItem[1])
        if (
          checkItem[1][checkItem[1].length - 1].examineStatusCode % 10 ===
          2
        ) {
          checkItem[1].push(item);
        }
      }
    }
  }
};

// 获取驳回记录
const getRejectCheckList = (checkList: any, stage: number) => {
  // 找到最后一个重新提交的位置
  console.log(checkList);

  const lastIndex = lastRemedyIndex(checkList);
  console.log("最后一个重新提交的索引", lastIndex);
  // 拿到最后一个重新提交的记录
  if (lastIndex > -1) {
    // 如果找到了 拿到这个提交之后的记录
    checkList = checkList.slice(lastIndex + 1);
  }
  console.log(checkList);

  if (stage === 50) {
    // examineStatusCode为5的那个节点索引
    const platformFiveIndex = checkList.findIndex(
      (item: any) => item.examineStatusCode === 5,
    );
    // 因为没有终止，所以只可能有一个examineStatusCode为5,找到examineStatusCode为5的索引
    const platformIndex = checkList.findIndex(
      (item: any) => item.examineStatusCode === 5,
    );
    // 拿到平台部分,筛选掉提交部分
    rejectCheckList.value = checkList
      .slice(platformIndex + 1)
      .filter(
        (item) =>
          item.examineStatusCode != 0 &&
          item.examinerId === currentExaminerId.value &&
          item.examineStatusCode % 10 === 2,
      );
  } else {
    // 过滤掉出驳回的记录
    rejectCheckList.value = checkList.filter((item: any) => {
      return (
        item.examineStatusCode > stage &&
        item.examineStatusCode < stage + 10 &&
        item.examineStatusCode % 10 === 2
      );
    });
  }

  // 倒序
  console.log(rejectCheckList.value, checkList, stage);

  rejectCheckList.value.reverse();
};

// 两级审核的记录
const schoolCheckList: any = ref([]);
// 获取校长审核页面的审核记录
const getSchoolCheckList = (checkList: any) => {
  // 如果终止过
  // 找到最后一个终止的位置
  const lastIndex = lastRemedyIndex(checkList);
  console.log("最后一个重新提交的索引", lastIndex);
  // 拿到最后一个重新提交的记录
  if (lastIndex > -1) {
    // 如果找到了 拿到这个提交之后的记录
    checkList = checkList.slice(lastIndex + 1);
  }
  // 过滤掉出驳回的记录
  schoolCheckList.value = checkList.filter((item: any) => {
    return item.examineStatusCode != 0;
  });
  // 溢出最后一个
  schoolCheckList.value.pop();
  // 倒序
  schoolCheckList.value.reverse();
};

// 获取审核记录BO
const getCheckRecordBO = ref({
  // 课程id
  sourceId: "",
  pageSize: 50,
  pageNum: 1,
  orderByColumn: "createTime",
  orderType: "asc",
});
const currentExaminerId = ref();
const otherExportCheckList = ref([]);
// 详情按钮
const handleDetail = async (row: any, isOperate?: boolean) => {
  console.log(row);
  // 如果有审核者id则保存
  if (row.examinerId) {
    currentExaminerId.value = row.examinerId;
  }
  if (row.status === "0") {
    // 待审核和审核中列表
    if (row.examineStatusCode === 5 && isExpert) {
      // 内容审核池列表的审核按钮
      const [err, preemptRes] = await to(preemptCheckTaskApi(row.id));
      if (!err) {
        console.log(preemptRes);
        // 待审核列表的审核按钮
        dialogStatus.value.isContentDetail = true;
        dialogStatus.value.title = "课程详情";
        // 获取课程详情
        const [courseErr, courseRes] = await to(
          getCourseDetailApi(row.sourceId),
        );
        if (!courseErr) {
          courseInfo.value = courseRes.data;
          courseInfo.value.isOperate = isOperate as boolean;
          if (courseInfo?.value!.category) {
            courseInfo.value!.categoryId = (
              courseInfo?.value!.category as any
            ).id;
          }
        }
        // 获取审核任务详情
        const [taskErr, taskRes] = await to(
          getCheckTaskDetailApi(preemptRes.data),
        );
        if (!taskErr) {
          console.log(taskRes);
          checkTaskBO.value = taskRes.data;
          // 如果打分字段为null
          if (!taskRes.data.additionalDataList) {
            checkTaskBO.value.additionalDataList = [
              {
                dataType: "courseScore",
                score: 0,
                type: "1",
              },
              {
                dataType: "courseScore",
                score: 0,
                type: "2",
              },
              {
                dataType: "courseScore",
                score: 0,
                type: "3",
              },
            ];
          }
        } else {
          console.log(taskErr);
        }
      } else {
        ElMessage({
          type: "error",
          message: "审核失败",
        });
      }
    } else if (row.examineStatusCode === 30) {
      // 校长待审核列表
      // 获取当前课程id
      getCheckRecordBO.value.sourceId = row.sourceId;
      // 获取当前课程id所有记录
      const [err, recordRes] = await to(
        getCheckRecordApi(getCheckRecordBO.value),
      );
      if (!err) {
        console.log(recordRes);

        // 获取记录中校长审核之前的两条通过
        getSchoolCheckList(recordRes.rows);
        console.log(schoolCheckList.value);
        // 待审核列表的审核按钮
        dialogStatus.value.title = "课程审核";
        dialogStatus.value.isFirstDetail = true;
        // 获取课程详情
        const [courseErr, courseRes] = await to(
          getCourseDetailApi(row.sourceId),
        );
        if (!courseErr) {
          courseInfo.value = courseRes.data;
          courseInfo.value.isOperate = isOperate as boolean;
          if (courseInfo?.value!.category) {
            courseInfo.value!.categoryId = (
              courseInfo?.value!.category as any
            ).id;
          }
        }
        // 获取审核任务详情
        const [err, res2] = await to(getCheckTaskDetailApi(row.id));
        if (!err) {
          checkTaskBO.value = res2.data;
          // 如果打分字段为null
          if (!res2.data.additionalDataList) {
            checkTaskBO.value.additionalDataList = [
              {
                dataType: "courseScore",
                score: 0,
                type: "1",
              },
              {
                dataType: "courseScore",
                score: 0,
                type: "2",
              },
              {
                dataType: "courseScore",
                score: 0,
                type: "3",
              },
            ];
          }
        } else {
          console.log(err);
        }
      }
    } else {
      // 其他审核中/待审核列表
      // 获取当前课程id
      getCheckRecordBO.value.sourceId = row.sourceId;
      // 获取当前课程id所有记录
      const [err, recordRes] = await to(
        getCheckRecordApi(getCheckRecordBO.value),
      );
      if (!err) {
        console.log(row.examineStatusCode / 10);
        // 获取记录中校长审核之前的两条通过
        getRejectCheckList(recordRes.rows, row.examineStatusCode);
        console.log(rejectCheckList.value);
        // 待审核列表的审核按钮
        dialogStatus.value.title = "课程审核";
        dialogStatus.value.isFirstDetail = true;
        // 获取课程详情
        const [courseErr, courseRes] = await to(
          getCourseDetailApi(row.sourceId),
        );
        if (!courseErr) {
          courseInfo.value = courseRes.data;
          courseInfo.value.isOperate = isOperate as boolean;
          if (courseInfo?.value!.category) {
            courseInfo.value!.categoryId = (
              courseInfo?.value!.category as any
            ).id;
          }
        }

        // 获取审核任务详情
        const [taskErr, taskRes] = await to(getCheckTaskDetailApi(row.id));
        if (!taskErr) {
          console.log(taskRes);
          checkTaskBO.value = taskRes.data;
          // 如果打分字段为null
          if (!taskRes.data.additionalDataList) {
            checkTaskBO.value.additionalDataList = [
              {
                dataType: "courseScore",
                score: 0,
                type: "1",
              },
              {
                dataType: "courseScore",
                score: 0,
                type: "2",
              },
              {
                dataType: "courseScore",
                score: 0,
                type: "3",
              },
            ];
          }
        } else {
          console.log(err);
        }
      }
    }
  } else {
    //  已审核列表
    if (row.examineStatusCode > 50 && row.examineStatusCode < 60) {
      // 平台阶段
      dialogStatus.value.title = "课程详情";
      dialogStatus.value.isSecondDetail = true;
      // 获取课程详情
      const [courseErr, courseRes] = await to(getCourseDetailApi(row.sourceId));
      if (!courseErr) {
        courseInfo.value = courseRes.data;
        courseInfo.value.isOperate = isOperate as boolean;
        if (courseInfo?.value!.category) {
          courseInfo.value!.categoryId = (
            courseInfo?.value!.category as any
          ).id;
        }
      }

      // 获取审核任务详情
      const [taskErr, taskRes] = await to(getCheckTaskDetailApi(row.id));
      if (!taskErr) {
        checkTaskBO.value = taskRes.data;
        // 如果打分字段为null
        if (!taskRes.data.additionalDataList) {
          checkTaskBO.value.additionalDataList = [
            {
              dataType: "courseScore",
              score: 0,
              type: "1",
            },
            {
              dataType: "courseScore",
              score: 0,
              type: "2",
            },
            {
              dataType: "courseScore",
              score: 0,
              type: "3",
            },
          ];
        }
        console.log(checkTaskBO.value);
      }
      getCheckRecordBO.value.sourceId = row.sourceId;
      // 拿到其他专家最新的审核记录
      const [recordErr, recordRes] = await to(
        getCheckRecordApi(getCheckRecordBO.value),
      );
      if (!recordErr) {
        console.log(recordRes);
        // 过滤掉运营审核部分和跟着有关的审核部分
        recordRes.rows = recordRes.rows.filter(
          (item: any) =>
            item.examineStatusCode < 60 && item.examinerId != row.examinerId,
        );
        // 拿到上一次重新提交之后的记录
        const lastResubmitIndex = findLastResubmitIndex(recordRes.rows);
        if (lastResubmitIndex > -1) {
          recordRes.rows = recordRes.rows.slice(lastResubmitIndex + 1);
        }
        // 拿到提交平台的索引
        const fiveCodeIndex = recordRes.rows.findIndex(
          (item) => item.examineStatusCode === 5,
        );
        // 拿到平台部分
        const currentPlatformList = recordRes.rows.slice(fiveCodeIndex);
        // 拿到另外两个专家的审核记录
        getEachExportCheckList(currentPlatformList);
        for (let item of exportMap) {
          // 找到每一个专家的最后的审核结果
          const lastCheckIndex = findExportFinalCheck(item[1]);
          // 添加到其他专家审核结果数组里面
          otherExportCheckList.value.push(item[1][lastCheckIndex]);
        }
        console.log(otherExportCheckList.value);
        // getOtherExpertCheckResult();
      } else {
        console.log(recordErr);
      }
    } else {
      // 其他阶段
      dialogStatus.value.title = "课程详情";
      dialogStatus.value.isSecondDetail = true;
      // 获取课程详情
      const res = await getCourseDetailApi(row.sourceId);
      courseInfo.value = res.data;
      courseInfo.value.isOperate = isOperate as boolean;
      if (courseInfo?.value!.category) {
        courseInfo.value!.categoryId = (courseInfo?.value!.category as any).id;
      }
      // 获取审核任务详情
      const [err, res2] = await to(getCheckTaskDetailApi(row.id));
      if (!err) {
        console.log(res2);
        checkTaskBO.value = res2.data;
        // 如果打分字段为null
        if (!res2.data.additionalDataList) {
          checkTaskBO.value.additionalDataList = [
            {
              dataType: "courseScore",
              score: 0,
              type: "1",
            },
            {
              dataType: "courseScore",
              score: 0,
              type: "2",
            },
            {
              dataType: "courseScore",
              score: 0,
              type: "3",
            },
          ];
        }
      } else {
        console.log(err);
      }
    }
  }
};

// 获取上次重新提交的记录
const findLastResubmitIndex = (list: any) => {
  let lastIndex = -1;
  for (let i = list.length - 1; i >= 0; i--) {
    if (list[i].examineStatusCode === 0 && !list[i].remedy) {
      lastIndex = i;
      break;
    }
  }
  return lastIndex;
};

// 获取每个专家的最后一个审核记录
const findExportFinalCheck = (list: any) => {
  let lastIndex = -1;
  for (let i = list.length - 1; i >= 0; i--) {
    if (list[i].examineStatusCode != 0 && list[i].examineStatusCode % 10 != 0) {
      lastIndex = i;
      break;
    }
  }
  return lastIndex;
};
const currentCheckDetail = ref();

// 关闭前的回调
const isClose = async (done: DoneFn) => {
  console.log(1);
  const [err, res2] = await to(getCheckTaskDetailApi(checkTaskBO.value.id));
  if (!err) {
    // 拿到当前后端保存的审核值
    currentCheckDetail.value = res2.data;
    // 如果打分字段为null
    if (!res2.data.additionalDataList) {
      currentCheckDetail.value.additionalDataList = [
        {
          dataType: "courseScore",
          score: 0,
          type: "1",
        },
        {
          dataType: "courseScore",
          score: 0,
          type: "2",
        },
        {
          dataType: "courseScore",
          score: 0,
          type: "3",
        },
      ];
    }
  }
  console.log(checkTaskBO.value, currentCheckDetail.value);

  if (
    checkTaskBO.value.reason == currentCheckDetail.value.reason &&
    JSON.stringify(checkTaskBO.value.additionalDataList) ==
      JSON.stringify(currentCheckDetail.value.additionalDataList)
  ) {
    // 如果相等则直接关闭
    done();
  } else {
    const [err] = await to<string, string>(
      ElMessageBox.confirm("您有修改且未保存的内容，是否要退出？", "警告", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning",
      }),
    );
    if (!err) {
      done();
    } else {
      ElMessage({
        type: "info",
        message: "取消成功",
      });
    }
  }
};
// 关闭dialog
const closeDialog = async () => {
  dialogStatus.value = Object.assign({}, initDialogStatus);
  checkTaskBO.value = Object.assign({}, initCheckTaskBO);
  schoolCheckList.value = [];
  rejectCheckList.value = [];
  getUnCheckList();
  getCheckedList();
  getContentPoolList();
  exportMap.clear();
  otherExportCheckList.value = [];
};

// 列表选中变化时触发
const handleSelectionChange = (selection: any) => {
  tableIds.value = selection.map((item: any) => item.id);
  console.log(tableIds.value);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

// 点击tab事件
const tabClick = (tab: any) => {
  console.log(tab.props.label);

  if (isExpert.value) {
    if (tab.props.label === "待审核") {
      console.log(1);

      getContentPoolList();
    } else if (tab.props.label === "审核中") {
      getUnCheckList();
    } else if (tab.props.label === "已审核") {
      getCheckedList();
    }
  } else {
    if (tab.props.label === "待审核") {
      getUnCheckList();
    } else if (tab.props.label === "已审核") {
      getCheckedList();
    }
  }
};

onMounted(() => {
  getRegionTree();
  getUserId();
  if (isExpert.value) {
    getContentPoolList();
  } else {
    getUnCheckList();
  }
});
</script>

<style scoped></style>
